package cn.hy.shortUrl.controller;

import cn.hy.shortUrl.entity.R;
import cn.hy.shortUrl.service.ShortLinkV1ServiceImpl;
import cn.hy.shortUrl.util.HashUtils;
import cn.hy.shortUrl.util.UrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.atomic.AtomicLong;


@Controller
@Slf4j
public class IndexController {

	@Autowired
	private ShortLinkV1ServiceImpl shortLinkServiceImpl;
	private static String host;

	private AtomicLong count = new AtomicLong(0);

	@Value("${server.host}")
	public void setHost(String host) {
		this.host = host;
	}

	@GetMapping("/")
	public String index() {
		return "index";
	}

	@PostMapping("/generate")
	@ResponseBody
	public R generateShortURL(@RequestParam String longURL) {
		if (UrlUtils.checkURL(longURL)) {
			if (!longURL.startsWith("http")) {
				longURL = "http://" + longURL;
			}
			String shortURL = shortLinkServiceImpl.save(longURL);
			return R.ok("请求成功", host + shortURL);
		}
		return R.create(400, "URL有误");
	}

	//设计一个key
	//短域名 + key

	@GetMapping("/{shortURL}")
	public String redirect(@PathVariable String shortURL) {
		String longURL = shortLinkServiceImpl.lookup(shortURL);
		if (longURL != null) {
			// shortUrlService.updateUrlViews(shortURL);
			// 查询到对应的原始链接，302重定向
			return "redirect:" + longURL;
		}
		//没有对应的原始链接，直接返回首页
		return "redirect:/";
	}



	@GetMapping("/name")
	@ResponseBody
	public String name(String name) {
		log.info("调用次数:{}", count.incrementAndGet());
		return "调用" + name ;
	}
}
